package utils

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
	"crypto/md5"
)

//func main() {
//	arr := []string{"zhangsan", "张三", "18022334281"}
//	orig := strings.Join(arr, ",")
//	fmt.Println("checkData：", orig)
//	md5byte := GetStringMd5(orig)
//	//orig := "c8b7b2ff5f9c9155bb5e82ffb69a57b8"
//	key, _ := base64.StdEncoding.DecodeString("bGVhcm5fa2V5")
//	fmt.Println("key：", string(key))
//	fmt.Println("原文：", orig)
//	fmt.Println("原文md5：", hex.EncodeToString(md5byte))
//
//	encryptCode, _ := DesEncrypt(md5byte, key)
//	fmt.Println("密文：", hex.EncodeToString(encryptCode))
//
//	decryptCode, _ := DesDecrypt(encryptCode, key)
//	fmt.Println("解密结果：",hex.EncodeToString(decryptCode))
//}

//加密
func DesEncrypt(origData []byte, key []byte) ([]byte, error) {
	if len(key) > 8 {
		key = key[:8]
	}
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	origData = PKCS5Padding(origData, block.BlockSize())
	blockMode := cipher.NewCBCEncrypter(block, key)
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

//解密
func DesDecrypt(crypted, key []byte) ([]byte, error) {
	if len(key) > 8 {
		key = key[:8]
	}
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockMode := cipher.NewCBCDecrypter(block, key)
	origData := make([]byte, len(crypted))
	// origData := crypted
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS5UnPadding(origData)
	// origData = ZeroUnPadding(origData)
	return origData, nil
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unpadding 次
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

//计算MD5
func GetByteMd5(s []byte) []byte {
	md5 := md5.New()
	md5.Write(s)
	//md5Str := hex.EncodeToString(md5.Sum(nil))
	return md5.Sum(nil)
}

//计算MD5
func GetStringMd5(s string) []byte {
	md5 := md5.New()
	md5.Write([]byte(s))
	//md5Str := hex.EncodeToString(md5.Sum(nil))
	return md5.Sum(nil)
}
